<?php
// core/MiddlewareHandler.php - Optimized middleware pipeline
declare(strict_types=1);

namespace core;

use Closure;
use Exception;

class MiddlewareHandler
{
    private array $middleware = [];
    private static array $instances = []; // Cache middleware instances
    private static array $validated = []; // Cache validation results

    public function add(string $middleware): self
    {
        // Validate middleware class once during registration
        if (!isset(self::$validated[$middleware])) {
            if (!class_exists($middleware)) {
                throw new Exception("Middleware class not found: {$middleware}", 500);
            }
            // if (!(new $middleware()) instanceof MiddlewareInterface) {
            //     throw new Exception("{$middleware} must implement MiddlewareInterface", 500);
            // }
            self::$validated[$middleware] = true;
        }
        $this->middleware[] = $middleware;
        return $this;
    }

    public function handle(Request $request, Closure $destination): void
    {
        // Build pipeline efficiently
        $stack = $destination;
        foreach (array_reverse($this->middleware) as $middleware) {
            // Reuse cached instance or create new one
            if (!isset(self::$instances[$middleware])) {
                self::$instances[$middleware] = new $middleware();
            }

            $stack = fn (Request $req) => self::$instances[$middleware]->handle($req, $stack);
        }

        $stack($request);
    }

    // Clear cached instances (useful for testing or long-running processes)
    public static function clearCache(): void
    {
        self::$instances = [];
        self::$validated = [];
    }
}
